import Vue from 'vue'
import Router from 'vue-router'
import Home from '../views/Home'
import Topic from '../views/Topic'
import Category from '../views/Category'
import Cart from '../views/Cart'
import User from '../views/User'
import ProductDetail from '../views/ProductDetail'

// 先把VueRouter原型对象的push，先保存一分
let originPush = Router.prototype.push;

Router.prototype.push = function(location, resolve, reject) {
  if (resolve && reject) {
    // call||apply都可以调用函数一次，都可以篡改函数上下文一次 call传递参数用逗号隔开，apply方法执行，传递数组
    originPush.call(this, location, resolve, reject);
  } else {
    originPush.call(
      this,
      location,
      () => {},
      () => {}
    );
  }
};

Router.prototype.replace = function(location, resolve, reject) {
  if (resolve && reject) {
    originReplace.call(this, location, resolve, reject);
  } else {
    originReplace.call(
      this,
      location,
      () => {},
      () => {}
    );
  }
};



Vue.use(Router)


// 路由拦截 （导航守卫，前置导航守卫，后置导航守卫）

const routes = [
  {
    path: "/",
    redirect: "/home"
  },
  {
    path:'/home',
    name:"Home",
    component:Home,
    // 元数据对象（标签）
    meta:{
      num:0,
      isShowTabbar:true
    },
    children:[
      {
        path:'popup',
        name:'myPopup',
        component:() => import(/* webpackChunkName: "group-foo" */ '../views/myPopup')
      }
    ]
  },
  {
    path:'/topic',
    name:'Topic',
    component:Topic,
    meta:{
      num:1,
      isShowTabbar:true
    },
  },
  {
    path:'/category',
    name:'Category',
    component:Category,
    meta:{
      num:2,
      isShowTabbar:true
    },
  },
  {
    path:'/cart',
    name:'Cart',
    component:Cart,
    meta:{
      num:3,
      isShowTabbar:true
    },
  },
  {
    path:'/user',
    name:'User',
    component:User,
    meta:{
      num:4,
      isShowTabbar:true
    },
  },
  {
    path:'/productdetail',
    name:'ProductDetail',
    component:ProductDetail,
  }

]


const router1 = new Router({
  mode:'history',
  base:'/testvue/',
  routes
})

// 路由文件有没有this指向
// 路由没有this 只能在vue的原型上挂载(Vue.prototype)

router1.beforeEach((to,from,next)=>{
  let token = localStorage.getItem('token')
  if(to.path=="/cart"){
    // 此时必须要有token
    if(token){
      next();
    }else{
      Vue.prototype.$toast('请先登录');
      setTimeout(()=>{
        next('/user')
      },1000)
    }
    return;
  }
  next()
})


export default router1
